package cn.itcast.service.cargo.impl;

import cn.itcast.dao.cargo.ContractDao;
import cn.itcast.dao.cargo.ExtCproductDao;
import cn.itcast.domain.cargo.Contract;
import cn.itcast.domain.cargo.ExtCproduct;
import cn.itcast.domain.cargo.ExtCproductExample;
import cn.itcast.service.cargo.ExtCproductService;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.UUID;

@Service
public class ExtcProductServiceImpl implements ExtCproductService {
    @Autowired
    private ExtCproductDao extCproductDao;
    @Autowired
    private ContractDao contractDao;

    @Override
    public void save(ExtCproduct extCproduct) {
        //附件的ID和总金额
        extCproduct.setId(UUID.randomUUID().toString().replaceAll("-",""));
        Double total = extCproduct.getPrice() * extCproduct.getCnumber();
        extCproduct.setAmount(total);

        //保存附件
        extCproductDao.insertSelective(extCproduct);
        //修改附件后要修改连带的合同总金额、合同上附件的数量、并修改合同
        Contract contract = contractDao.selectByPrimaryKey(extCproduct.getContractId());
        contract.setTotalAmount(contract.getTotalAmount()+total);
        contract.setExtNum(contract.getExtNum()+1);
        contractDao.updateByPrimaryKeySelective(contract);
    }

    @Override
    public void update(ExtCproduct extCproduct) {
        //获取修改前的附件对象、修改前的货物总金额
        //计算最新的总金额赋值给货物并更新
        //修改合同总金额。
        //修改合同
        ExtCproduct old_ext = extCproductDao.selectByPrimaryKey(extCproduct.getId());
        Double old_extAmount = old_ext.getAmount();
        Double new_total = extCproduct.getPrice() * extCproduct.getCnumber();
        extCproduct.setAmount(new_total);

        Contract contract = contractDao.selectByPrimaryKey(extCproduct.getContractId());
        contract.setTotalAmount(contract.getTotalAmount()-old_extAmount+new_total);
        contractDao.updateByPrimaryKeySelective(contract);
    }

    @Override
    public void delete(String id) {
        ExtCproduct extCproduct = extCproductDao.selectByPrimaryKey(id);
        //获取附件总金额
        Double total = extCproduct.getAmount();
        extCproductDao.deleteByPrimaryKey(id);

        //修改合同
        //包括合同的总金额，附件数量，更新最新的合同
        Contract contract = contractDao.selectByPrimaryKey(extCproduct.getId());
        contract.setTotalAmount(contract.getTotalAmount()-total);
        contract.setExtNum(contract.getExtNum()-1);
        contractDao.updateByPrimaryKeySelective(contract);
    }

    @Override
    public ExtCproduct findById(String id) {
        return extCproductDao.selectByPrimaryKey(id);
    }

    @Override
    public PageInfo findAll(ExtCproductExample example, int page, int size) {
        PageHelper.startPage(page, size);
        List<ExtCproduct> list = extCproductDao.selectByExample(example);

        return new PageInfo(list);
    }
}
